package com.ruoyi.web.controller.danger;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSON;
import com.alibaba.fastjson.JSONObject;
import com.magus.OPException;
import com.magus.jdbc.OPResultSet;
import com.magus.opio.dto.OPConst;
import com.magus.opio.dto.OPTable;
import com.magus.opio.net.IOPConnect;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.opio.util.ExampleBase;
import com.ruoyi.common.opio.util.OPPool;
import com.ruoyi.common.utils.ParseResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.vo.SysDangerPointResultVO;
import com.ruoyi.system.entity.SysDangerPoint;
import com.ruoyi.system.service.SysDangerPointService;
import com.ruoyi.system.service.impl.SysDangerPointServiceImpl;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;

/**
 * (SysDangerPoint)表控制层
 * @since 2022-11-22 09:55:00
 */
@Slf4j
@RestController
@RequestMapping("sysDangerPoint")
public class SysDangerPointController extends BaseController {

    @Resource
    private SysDangerPointService sysDangerPointService;

    @Resource
    private SysDangerPointServiceImpl sysDangerPointServicei;

    /**
     * 分页查询
     * @param sysDangerPoint 筛选条件
     * @return 查询结果
     */
    @GetMapping("/list")
    public TableDataInfo queryByPage(SysDangerPoint sysDangerPoint) {
        startPage();
        List<SysDangerPoint> sysDangerPoints = this.sysDangerPointService.queryByPage(sysDangerPoint);
        return getDataTable(sysDangerPoints);
    }

    /**
     * 通过主键查询单条数据
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public AjaxResult queryById(@PathVariable("id") Integer id) {
        return AjaxResult.success(this.sysDangerPointService.queryById(id));
    }

    /**
     * 新增数据
     * @param sysDangerPoint 实体
     * @return 新增结果
     */
    @PostMapping("/create")
//    @PreAuthorize("@ss.hasPermi('sysDangerPoint:create')")
    public AjaxResult add(@RequestBody SysDangerPoint sysDangerPoint) {
        return AjaxResult.success(this.sysDangerPointService.insert(sysDangerPoint));
    }

    /**
     * 编辑数据
     * @param sysDangerPoint 实体
     * @return 编辑结果
     */
    @PostMapping("/update")
//    @PreAuthorize("@ss.hasPermi('sysDangerPoint:update')")
    public AjaxResult edit(@RequestBody SysDangerPoint sysDangerPoint) {
        return AjaxResult.success(this.sysDangerPointService.update(sysDangerPoint));
    }

    /**
     * 删除数据
     * @param id 主键
     * @return 删除是否成功
     */
    @GetMapping("/delete")
//    @PreAuthorize("@ss.hasPermi('sysDangerPoint:delete')")
    public AjaxResult deleteById(Integer id) {
        return AjaxResult.success(this.sysDangerPointService.deleteById(id));
    }

    /**
     * 与实时数据库关联
     * @return
     */
    @GetMapping("/getTimeData")
    public TableDataInfo getTimeData(SysDangerPoint query) {
        startPage();
        List<SysDangerPoint> sysDangerPoints = this.sysDangerPointService.queryByPage(query);
        Map<String, Object> map = ExampleBase.toResult();
        if (CollUtil.isNotEmpty(map)) {
            log.info(" 请求 OPC， 获取到液位信息： {}", JSONObject.toJSONString(map));
            sysDangerPoints.forEach(sysDangerPoint -> {
                if (map.containsKey(sysDangerPoint.getBitNumber())) {
                    Object o = map.get(sysDangerPoint.getBitNumber());
                    if (o!=null && compare(o.toString())) {
                        sysDangerPoint.setAv("0.000");
                    } else {
                        assert o != null;
                        sysDangerPoint.setAv(o.toString());
                    }
                }
            });
        }
        return getDataTable(sysDangerPoints);
    }

    public static boolean compare(String decimal) {
        BigDecimal bd1 = new BigDecimal(decimal);
        BigDecimal bd2 = new BigDecimal(25);
        return bd1.compareTo(bd2) >= 0;
    }

    /**
     * 与实时数据库关联桶展示
     * @return
     */
    @GetMapping("/getData")
    public TableDataInfo getData(SysDangerPoint query) {
        List<SysDangerPoint> sysDangerPoints = this.sysDangerPointService.queryByPage(query);
        List<SysDangerPointResultVO> list = new ArrayList<>();
        Map<String, Object> map = ExampleBase.toResult();
        if (CollUtil.isNotEmpty(map)) {
            sysDangerPoints.forEach(sysDangerPoint -> {
                Boolean flag = true;
                for (SysDangerPointResultVO sysDangerPointResultVO : list) {
                    if (sysDangerPoint.getDeviceName().equals(sysDangerPointResultVO.getDeviceName())) {
                        String param = sysDangerPoint.getParam();
                        Object o = map.get(sysDangerPoint.getBitNumber());
                        if (null != o) {
                            if (param.equals("温度")) {
                                sysDangerPointResultVO.setTemperature(o.toString() + sysDangerPoint.getUnit());
                                sysDangerPointResultVO.setTemperatureNum(sysDangerPoint.getDatabaseBitNumber());
                            } else if (param.equals("液位")) {
                                if (o!=null && compare(o.toString())) {
                                    sysDangerPointResultVO.setLiquid("0.000" + sysDangerPoint.getUnit());
                                } else if (o != null) {
                                    sysDangerPointResultVO.setLiquid(o.toString() + sysDangerPoint.getUnit());
                                }
                                sysDangerPointResultVO.setLiquidNum(sysDangerPoint.getDatabaseBitNumber());
                            }
                        }
                        flag = false;
                    }
                }
                if (flag) {
                    SysDangerPointResultVO sysDangerPointResultVO = new SysDangerPointResultVO();
                    sysDangerPointResultVO.setDeviceName(sysDangerPoint.getDeviceName());
                    sysDangerPointResultVO.setDangerName(sysDangerPoint.getDangerName());
                    sysDangerPointResultVO.setUnitName(sysDangerPoint.getUnitName());
                    String param = sysDangerPoint.getParam();
                    Object o = map.get(sysDangerPoint.getBitNumber());
                    if (null != o) {
                        if (param.equals("温度")) {
                            sysDangerPointResultVO.setTemperature(o.toString() + sysDangerPoint.getUnit());
                            sysDangerPointResultVO.setTemperatureNum(sysDangerPoint.getDatabaseBitNumber());
                        } else if (param.equals("液位")) {
                            if (o!=null && compare(o.toString())) {
                                sysDangerPointResultVO.setLiquid("0.000" + sysDangerPoint.getUnit());
                            } else if (o != null) {
                                sysDangerPointResultVO.setLiquid(o.toString() + sysDangerPoint.getUnit());
                            }
                            sysDangerPointResultVO.setLiquidNum(sysDangerPoint.getDatabaseBitNumber());
                        }
                        list.add(sysDangerPointResultVO);
                    }
                }
            });
        } else {
            sysDangerPoints.forEach(sysDangerPoint -> {
                Boolean flag = true;
                for (SysDangerPointResultVO sysDangerPointResultVO : list) {
                    if (sysDangerPoint.getDeviceName().equals(sysDangerPointResultVO.getDeviceName())) {
                        String param = sysDangerPoint.getParam();
                        if (param.equals("温度")) {
                            sysDangerPointResultVO.setTemperature("0" + sysDangerPoint.getUnit());
                            sysDangerPointResultVO.setTemperatureNum(sysDangerPoint.getDatabaseBitNumber());
                        } else if (param.equals("液位")) {
                            sysDangerPointResultVO.setLiquid("0" + sysDangerPoint.getUnit());
                            sysDangerPointResultVO.setLiquidNum(sysDangerPoint.getDatabaseBitNumber());
                        }
                        flag = false;
                    }
                }
                if (flag) {
                    SysDangerPointResultVO sysDangerPointResultVO = new SysDangerPointResultVO();
                    sysDangerPointResultVO.setDeviceName(sysDangerPoint.getDeviceName());
                    sysDangerPointResultVO.setDangerName(sysDangerPoint.getDangerName());
                    sysDangerPointResultVO.setUnitName(sysDangerPoint.getUnitName());
                    String param = sysDangerPoint.getParam();
                    if (param.equals("温度")) {
                        sysDangerPointResultVO.setTemperature("0" + sysDangerPoint.getUnit());
                        sysDangerPointResultVO.setTemperatureNum(sysDangerPoint.getDatabaseBitNumber());
                    } else if (param.equals("液位")) {
                        sysDangerPointResultVO.setLiquid("0" + sysDangerPoint.getUnit());
                        sysDangerPointResultVO.setLiquidNum(sysDangerPoint.getDatabaseBitNumber());
                    }
                    list.add(sysDangerPointResultVO);
                }
            });
        }
        return getDataTable(list);
    }

    /**
     * 与历史数据库关联
     * @return
     */
    @GetMapping("/getFindArchive")
    public TableDataInfo getFindArchive(SysDangerPoint query) throws OPException, SQLException {
        startPage();
        IOPConnect conn = OPPool.getConn();//获取连接
        OPTable table = conn.createTable(OPConst.TABLE_ARCHIVE);//创建模型table，历史表传入类为 "Archive"
        String[] str = {"GN", "AV", "TM", "DS"};
        table.addColumns(str);//声明需要查询的字段 历史表AV TM字段必须写入
        List<String> strList=new ArrayList<>();
        List<SysDangerPoint> sysDangerPoints = this.sysDangerPointService.queryByPage(query);
        if (!CollectionUtils.isEmpty(sysDangerPoints)){
            for (SysDangerPoint sysDangerPoint : sysDangerPoints) {
                strList.add(sysDangerPoint.getDatabaseBitNumber());
            }
            String[] points ={StringUtils.join(strList)};//创建测点唯一标识的数组   使用ID字段的话类型为int[]或者long[]
            //查询之前一个小时的历史
            Date end = new Date();
            Date start = new Date(end.getTime() - 3600000);
            /**
             *OPConst.Archive_Model.raw为查历史的类型
             * raw：原始值(加开始结束时间),arch:原始值, span：等间距, plot：绘图值,
             * flow：流量值, max：最大值, min：最小值, avg：面积平均值, mean：算术平均值
             * prev:原始值结果增加采集值时间区间前第一个值,next:原始值结果增加采集值时间区间后第一个值,
             * both:原始值前后各增加最近一条的记录
             * interval为1 是在按等间距取值  单位是秒  如果是原始值则不生效
             */
            OPResultSet result = conn.findArchive(table, points, start, end, OPConst.Archive_Model.raw, 1);//查询历史

            ParseResult.printResult(result);//解析结果集并打印出来
            result.close();//关闭结果集
            table.destroy();//销毁模型table
            OPPool.freeConn(conn);//释放连接
        }
        return getDataTable(sysDangerPoints);
    }

    /**
     *
     * @return
     * @throws TemplateException
     * @throws IOException
     */
    @GetMapping("/createFile")
    public AjaxResult createFile() throws TemplateException, IOException {
        sysDangerPointServicei.createDroolsFile();
        return AjaxResult.success();
    }

    /**
     *
     * @return
     */
    @GetMapping("/reload")
    public AjaxResult reload(){
        sysDangerPointServicei.reload();
        return AjaxResult.success();
    }

    /**
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "重大危险源点位(", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception{
        ExcelUtil<SysDangerPoint> util = new ExcelUtil<>(SysDangerPoint.class);
        List<SysDangerPoint> sysDangerPoints= util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = sysDangerPointService.importExcel(sysDangerPoints, updateSupport, operName);
        return success(message);
    }

    /**
     *
     * @param response
     * @param sysDangerPoint
     */
    @Log(title = "重大危险源点位(", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysDangerPoint sysDangerPoint)
    {
        List<SysDangerPoint> sysDangerPoints = this.sysDangerPointService.queryByPage(sysDangerPoint);
        ExcelUtil<SysDangerPoint> util = new ExcelUtil<>(SysDangerPoint.class);
        util.exportExcel(response, sysDangerPoints, "重大危险源点位(");
    }

    /**
     *
     * @param response
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysDangerPoint> util = new ExcelUtil<>(SysDangerPoint.class);
        util.importTemplateExcel(response,"重大危险源点位(");
    }









}

